package com.hx.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * @author xushu
 * @date 2024 下午8:40
 */
@Slf4j
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Autowired
    private WebSocketHandshakeInterceptor webSocketHandshakeInterceptor;
    @Autowired
    private AuthChannelInterceptor authChannelInterceptor;

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //允许使用socketJs方式访问，访问点为/websocket，允许跨域
        registry.addEndpoint("/websocket")
                //允许跨域
                .setAllowedOriginPatterns("*")
                //设置握手请求拦截器
                //拦截器方式1，不方便，不好用，请用下面拦截器方式2
                /*.addInterceptors(webSocketHandshakeInterceptor)
                .setHandshakeHandler(new DefaultHandshakeHandler() {
                    @Override
                    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
                        SysUser currentUser = (SysUser) attributes.get("currentUser");
                        log.info("通过拦截器，获取当前登陆用户{}", currentUser != null ? currentUser.getUsername() : "未获取到用户信息");
                        return currentUser;
                    }
                })*/
                .withSockJS();
    }
    /**
     * 拦截器方式2
     * Token 认证
     * @param registration {@link ChannelRegistration} 通道注册
     */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(authChannelInterceptor);
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //订阅Broker名称
        // 消息基于内存代理,向客户端发消息topic用来广播，queue用来实现p2p
        registry.enableSimpleBroker("/topic", "/queue");
        //全局使用的订阅前缀(客户端订阅路径上会体现出来)
        registry.setApplicationDestinationPrefixes("/app");
        //点对点使用的订阅前缀(客户端订阅路径上会体现出来)，不设置的话，默认也是/user
        registry.setUserDestinationPrefix("/user");
    }
}
